<template>
  <div class="authenticate">

    <div class="tit">
      <span
        class="goback" style="font-size: .2rem;font-weight: 700;">分类鉴定</span>
      <span style="font-size: .2rem;margin:0 .1rem;">></span>
      <span style="font-size: .2rem;font-weight: 700;">{{$route.query.keyword}}</span>
      <div style="position: absolute;right: .2rem;">
        <el-button @click="goback" size="small">结束鉴定</el-button>
      </div>
    </div>

    <!--主要容器-->
    <div class="aut_main" v-if="islast">
      <div class="aut_main_l" style="margin-top: .2rem;flex: 5;overflow: hidden">
        <!--大图-->
        <div class="big_image">
          <!--set-->
          <div class="big_image_set">
            <div @click="l_b_img" class="alpt" title="查看大图">
              <viewer :images="signImages" style="opacity: 0">
                <img v-for="src in signImages" :src="src" :key="src" width="50">
              </viewer>
              <!--<img src="../../static/images/alpt.png" alt="">-->
            </div>
            <div @click="rp" title="查看对比图">
              <img src="../../static/images/对比.png" alt="">
            </div>
            <div @click="openTip" v-if="abilityList.indexOf('edit') != -1" title="自动识别">
              <img src="../../static/images/扫一扫.png" alt="">
            </div>

            <div @click="del" v-if="abilityList.indexOf('edit') != -1" title="删除">
              <img src="../../static/images/del.png" alt="">
            </div>
          </div>
          <!--set-->
          <!--图片-->
          <img class="big_image_img"
               v-show="isMp4(bigimage)=='照片'"
               id="pcr"
               :src="bigimage" alt="">
          <video style="width: 100%;height: 100%;" v-show="isMp4(bigimage)=='视频'" :src="bigimage" autoplay
                 controls></video>
          <!--图片-->
          <!--文字-->
          <div class="big_image_txt">
            <!--<span>拍摄时间：{{messageObj.shootingTime}}</span>-->
            &nbsp; &nbsp; &nbsp;
            <span>经度：{{ messageObj.lon }}</span>
            &nbsp; &nbsp; &nbsp;
            <span>纬度：{{ messageObj.lat }}</span>
          </div>
          <!--文字-->


          <div class="b_l_l" @click="bll">
            <img src="../../static/images/left.png" alt="">
          </div>

          <div class="b_r_r" @click="brr">
            <img src="../../static/images/right.png" alt="">
          </div>

        </div>
        <!--大图-->
        <!--小图-->
        <div class="small_image">
          <ul class="viewpager_container">
            <li v-for="(il,index) in imageList"
                @click="movement(il,index)"
                :style="il.color=='1'?'border: 2px solid #00CF3C;':'border: 1px solid #303133;'">
              <img v-show="isMp4(il.accessorySrc)=='照片'" :src="iscloud(il.accessorySrc)" alt="">
              <!--<video  :src="iscloud(il.accessorySrc)" controls autoplay></video>-->
              <img v-show="isMp4(il.accessorySrc)=='视频'" src="../../static/images/shipin.jpg" alt="">

              <div class="viewpager_container_li_txt">
                <span v-if="il.status == 'WAITING'" style="color: red">未处理</span>
                <span v-if="il.status == 'IDENTIFY'" style="color:#1FB456">已鉴定</span>
                <span v-if="il.status == 'PUBLISH'" style="color: #fff">已发布</span>
              </div>

            </li>
          </ul>
        </div>
        <!--小图-->
      </div>
      <div class="aut_main_r" style="flex: 5">
        <!--表单-->
        <div class="aut_main_r_form">
          <div style="background-color: #f4f6f8;padding-top: .2rem;overflow: hidden">
            <el-form
              style="width: 90%;"
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="120px"
              class="demo-ruleForm">
              <el-form-item label="拍摄时间" required>
                <!--prop="date"-->
                <el-form-item>
                  <el-date-picker
                    type="datetime"
                    placeholder="选择拍摄时间"
                    v-model="ruleForm.shootingTime"
                    :default-value="c_time(ruleForm.shootingTime)"
                    @change="gettime"
                    style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-form-item>

              <el-form-item label="物种类别" prop="objType">
                <el-radio-group v-model="ruleForm.objType">
                  <el-radio label="兽类"></el-radio>
                  <el-radio label="鸟类"></el-radio>
                  <el-radio label="两栖"></el-radio>
                  <el-radio label="其他"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="物种名称">
                <el-col :span="14">
                  <el-autocomplete
                    style="width: 100%;"
                    class="inline-input"
                    :fetch-suggestions="querySearch"
                    @focus="recently"
                    @input="sec"
                    placeholder="请输入物种名称"
                    v-model="ruleForm.speciesName"></el-autocomplete>
                </el-col>
                <!--<el-col class="line" :span="1">&nbsp;</el-col>-->
                <el-col :span="10">
                  <el-form-item label="无法鉴定">
                    <el-switch
                      @change="unableIdentifyFun"
                      v-model="delivery"></el-switch>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item label="鉴定人" prop="identifyPeople">
                <el-input v-model="ruleForm.identifyPeople"></el-input>
              </el-form-item>
              <el-form-item label="照片编号" prop="imageName">
                <el-input v-model="ruleForm.imageName"></el-input>
              </el-form-item>
              <el-form-item label="照片质量" prop="imageQuality">
                <el-select style="width: 100%;" v-model="ruleForm.imageQuality" placeholder="请选择照片质量">
                  <el-option label="低" value="低"></el-option>
                  <el-option label="中" value="中"></el-option>
                  <el-option label="高" value="高"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="物种数量" prop="animalNum">
                <el-input v-model.number="ruleForm.animalNum"></el-input>
              </el-form-item>
              <el-form-item label="物种性别" prop="speciesGender">
                <el-radio-group v-model="ruleForm.speciesGender">
                  <el-radio label="雄"></el-radio>
                  <el-radio label="雌"></el-radio>
                  <el-radio label="雄雌都有"></el-radio>
                  <el-radio label="难以辨别"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="温度(℃)" prop="temperature">
                <el-input v-model="ruleForm.temperature"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="ruleForm.remark"></el-input>
              </el-form-item>
            </el-form>
            <div style="display: flex;align-items:center;margin-left: 55px;margin-bottom: .1rem;"
                 v-if="abilityList.indexOf('edit') != -1">
              <div class="custombtn">
                <span @click="submitForm('ruleForm',1)" v-if="single">单张鉴定</span>
                <span @click="submitForm('ruleForm',2)" v-else>整组鉴定</span>
              </div>
              <div style="margin-left: .3rem;">
                <el-checkbox @change="issingle" v-model="single">只修改当前单张照片信息</el-checkbox>
              </div>
            </div>
          </div>

        </div>
        <!--表单-->
        <!--按钮-->

        <!--按钮-->
      </div>
    </div>
    <!--主要容器-->

    <!--自动识别组件-->
    <automatic ref="autoPhoto" :speciesData="animalData" v-on:nameCallBack="nameCall"></automatic>
    <!--自动识别组件-->

    <div class="areachart" v-if="isac">
      <div class="close" @click="acclose">
        <img src="../../static/images/icon/close.png" alt="">
      </div>

      <div class="acimg">
        <div class="original">
          <img style="width: 7.6rem;height: 5.7rem;" :src="accimg" alt="">
          <div style="position: absolute;top: 0;left: 0;">
            <img style="width: .6rem;height: .6rem;" src="../../static/images/yuantu.png" alt="">
          </div>
        </div>
        <div style="width: 1.6rem;height: 5.7rem;display: flex;align-items: center;justify-content: center">
          <div
            style="width: .8rem;height: .3rem;border-radius: .02rem;background-color: #000000 ;color: #FFFFFF;text-align: center;line-height: .3rem">
            <span>图片对比</span>
          </div>
        </div>
        <div class="similarity">
          <img style="width: 7.6rem;height: 5.7rem;" :src="acbimg" alt="">
          <div style="position: absolute;top: 0;left: 0;">
            <img style="width: .6rem;height: .6rem;" src="../../static/images/duibi.png" alt="">
          </div>
        </div>
      </div>
    </div>


  </div>
</template>
<script>
  import api from '../utils/api';
  import http from '../utils/http'
  import '../../static/jquery-ui-1.12.1/jquery-ui.css'
  import '../../static/jquery-ui-1.12.1/jquery-ui'

  export default {
    data() {
      return {
        single: false,
        animalData: {
          url: '',
          type: 'animal'
        },
        signImages: [''],
        indexes: 0,
        rm: 0,
        imageList: [],
        bigimage: "",
        messageObj: {},
        change_time: "",
        delivery: false,
        ruleForm: {
          id: "",
          shootingTime: '',//拍摄时间
          objType: '兽类',
          speciesName: '',//物种名称
          identifyPeople: "",//鉴定人
          imageName: "",//照片编号
          imageQuality: "",//照片质量
          animalNum: 1,//物种数量
          speciesGender: "",//物种性别
          temperature: '',//温度
          remark: ''
        },
        rules: {
          date: [
            {type: 'date', required: true, message: '请选择日期', trigger: 'change'}
          ],
          speciesName: [
            {required: true, message: '请输入物种名称', trigger: 'blur'}
          ],
          identifyPeople: [
            {required: true, message: '请输入鉴定人姓名', trigger: 'blur'}
          ],
          imageName: [
            {required: true, message: '请输入照片编号', trigger: 'blur'}
          ],
          imageQuality: [
            {required: true, message: '请选择照片质量', trigger: 'blur'}
          ],
          animalNum: [
            {required: true, message: '数量不能不能为空', trigger: 'blur'}
          ],
          objType: [
            {required: true, message: '请选择物种类别', trigger: 'blur'}
          ],
          speciesGender: [
            {required: true, message: '请选择物种性别', trigger: 'blur'}
          ],
        },
        areaId: "",
        //模糊搜索
        restaurants: [],
        obj: null,
        aclist: [],
        accimg: "",
        acbimg: "",
        acindex: 0,
        isac: false,
        imgimg: {},
        allnum: 0,
        nowpage: 1,
        groupId: "",
        tnumber: 1,
        cardxiaolei: "",
        groupNumber: "",
        userName: "",
        abilityList: [],
        islast: true
      }
    },
    created() {
      this.areaId = sessionStorage.getItem('areaId');
      this.cardxiaolei = this.$route.query.card;
      this.groupNumber = this.$route.query.groupNumber;
      this.nowpage = this.$route.query.index;
      this.allnum = this.$route.query.allnum;
      this.groupId = this.$route.query.groupId;
      this.userName = sessionStorage.getItem('urseName');
      if (localStorage.getItem('arr') == undefined) {
        let arr = [{value: "无识别结果"}];
        localStorage.setItem('arr', JSON.stringify(arr));
      }
      this.abilityList = sessionStorage.getItem('abilityList');
    },
    mounted() {
      this.getallImageIdentify();
    },
    methods: {
      issingle() {
        if (this.single) {
          this.ruleForm.aloneAuthenticate = 1;
        } else {
          this.ruleForm.aloneAuthenticate = 0;
        }
      },
      bll() {
        if (this.indexes > 0) {
          this.indexes--;
          this.movement2();
        }
      },
      brr() {
        if (this.indexes < this.imageList.length - 1) {
          this.indexes++;
          this.movement2();
        }
      },
      movement2() {
        if (this.imageList.length > 0) {
          let index = this.indexes;
          this.imageList.forEach(e => {
            e.color = '0'
          });
          let obj;
          if (index > this.imageList.length - 1) {
            obj = Object.assign({}, this.imageList[index - 1]);
            this.imageList[index - 1].color = '1';
          } else {
            obj = Object.assign({}, this.imageList[index]);
            this.imageList[index].color = '1';
          }
          this.getobj(obj);
          if (obj.discernPath != null) {
            this.bigimage = obj.discernPath;
          } else {
            this.bigimage = obj.accessorySrc;
          }

          this.animalData.url = obj.accessorySrc;
          let look_b_i = [];
          let ims = obj.accessorySrc
          look_b_i.push(ims);
          this.signImages = look_b_i;
          this.messageObj = Object.assign({}, obj);
          let target = $('.viewpager_container');
          if (index < this.imageList.length - 1 && index >= 3) {
            target.stop().animate({left: -(index - 2) * 1.6 + "rem"}, 500)
          } else if (index == 0) {
            target.stop().animate({left: 0}, 500)
          }
          $("#pcr").css("transform", "rotate(0deg)");
          let vm = this;
          $(function () {
            let maxWidth = $('.big_image').width();
            let maxHeight = $('.big_image').height();
            let path = $('#pcr').attr('src');
//          if (vm.isMp4(vm.Pictures) == '照片') {
            vm.AutoSize(path, maxWidth, maxHeight);
//          }
          })
        } else {
          this.eliminate();
        }
      },
      isMp4(m) {
        let iv = m.split('.');
        if (iv[iv.length - 1].toLowerCase() == 'mp4') {
          return '视频'
        } else {
          return '照片'
        }
      },
      eliminate() {
        this.bigimage = ""
        this.change_time = "";
        this.ruleForm.shootingTime = "";
        this.ruleForm.id = "";
        this.ruleForm.objType = "";
        this.ruleForm.speciesName = "";
        this.ruleForm.identifyPeople = "";
        this.ruleForm.imageName = "";
        this.ruleForm.imageQuality = "";
        this.ruleForm.animalNum = 1;
        this.ruleForm.speciesGender = "";
        this.ruleForm.temperature = "";
        this.ruleForm.remark = "";
      },
      //对比图左箭头
      acl() {
        let target = $("#acbox")
        if (this.acindex > 0) {
          this.acindex--;
          target.stop().animate({left: -this.acindex * 1.56 + "rem"}, 500);
          this.acbimg = this.aclist[this.acindex].path
          this.aclist.forEach(e => {
            e.color = '0'
          });
          this.aclist[this.acindex].color = '1';
        }
      },
      acr() {
        let target = $("#acbox")
        if (this.acindex < this.aclist.length - 1) {
          this.acindex++;
          target.stop().animate({left: -this.acindex * 1.56 + "rem"}, 500);
          this.acbimg = this.aclist[this.acindex].path;
          this.aclist.forEach(e => {
            e.color = '0'
          });
          this.aclist[this.acindex].color = '1';
        }
      },
      //无法鉴别
      unableIdentifyFun() {
        if (this.delivery) {
          this.ruleForm.speciesName = "无法鉴定"
        } else {
          this.ruleForm.speciesName = ""
        }
      },
      //模糊搜索
      querySearch(queryString, cb) {
        let restaurants = this.restaurants;
        if (restaurants.length > 0) {
          let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      },
      //模糊搜索2
      createFilter() {
        return (restaurant) => {
          return (restaurant.value.toLowerCase());
        };
      },
      //模糊搜索3
      loadAll() {
        return this.obj;
      },
      recently() {
        this.obj = JSON.parse(localStorage.getItem('arr'));
        this.restaurants = this.loadAll();
      },
      //模糊搜索4
      sec() {
        let vm = this;
        (async function () {
          let res = await http.get(api.queryByInput, {
            areaId: vm.areaId,
            type: vm.ruleForm.objType,
            input: vm.ruleForm.speciesName
          })
          let arr = [];
          if (res.data.length == 0) {
            vm.obj = [{value: "暂无数据，建议更换关键字"}];
            vm.restaurants = vm.loadAll();
          } else {
            res.data.forEach((e => {
              let z = {
                value: e
              }
              arr.push(z);
            }))
            vm.obj = arr;
            vm.restaurants = vm.loadAll();
          }
        })()
      },
      //提交
      submitForm(formName, flag) {
        let id = '';
        if (flag == 1) {
          id = this.ruleForm.id
        }
        if (flag == 2) {
          let arr = [];
          this.imageList.forEach(e => {
            arr.push(e.id)
          })
          id = arr.join(',')
        }
        let vm = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //            alert('submit!');
            if (this.ruleForm.shootingTime == '') {
              alert('拍摄时间不能为空');
              return false
            }
            (async function () {
              let res = await http.get(api.queryByInput, {
                areaId: vm.areaId,
                type: vm.ruleForm.objType,
                input: vm.ruleForm.speciesName
              })
              if (res.data.length == 0 && vm.ruleForm.speciesName != '无法鉴定') {
                vm.warn('物种名不存在，请重新填写物种名称');
                vm.ruleForm.speciesName = "";
                return false;
              } else {
                let obj = Object.assign({}, vm.ruleForm);
                obj['ids'] = id;
                obj.shootingTime = vm.change_time;
                (async function () {
                  let res = await http.post(api.infrared.newimageSave, obj)
                  if (res.data.message == 'error') {
                    vm.warn(res.data.error)
                  } else {
                    vm.getallImageIdentify();
                  }
                })()
              }
            })();
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //自动识别
      openTip() {
        this.$refs.autoPhoto.showtip();
        this.$refs.autoPhoto.openTip();
        this.$refs.autoPhoto.jcropDestroy();
      },
      nameCall(msg) {
        this.ruleForm.speciesName = msg;
      },
      acclose() {
        this.isac = false;
        this.acindex = 0;
      },
      rp() {
        let vm = this;
        (async function f() {
          let res = await http.get(api.compareImage, {
            input: vm.ruleForm.speciesName
          })
          if (res.data.code == '200') {
            vm.acbimg = res.data.data
          } else {
            vm.acbimg = "../../static/images/np.jpg";
          }
        })()
        this.isac = true;
        this.accimg = this.bigimage;
      },
      l_b_img() {
      },
      AutoSize(Img, maxWidth, maxHeight) {
        let image = new Image();
        image.src = Img;
        image.onload = function () {
          if (image.width < maxWidth && image.height < maxHeight) {
            $("#pcr").css({width: image.width, height: image.height})
          } else {
            if (maxWidth / maxHeight <= image.width / image.height) {
              $("#pcr").animate({width: maxWidth, height: maxWidth * (image.height / image.width)}, 'fast');
            } else {
              $("#pcr").animate({width: maxHeight * (image.width / image.height), height: maxHeight}, 'fast');
            }
          }
        }
      },
      getallImageIdentify() {
        let vm = this, keyword = this.$route.query.keyword, date = this.$route.query.date;
        (async function () {
          let res = await http.get('/iapi/authenticate/getNameGroupImages', {
            areaId: vm.areaId,
            date: date,
            keyword: keyword
          })
          if (res.data.data.length > 0) {
            res.data.data.forEach(e => {
              e['color'] = "0"
            })
            res.data.data[0].color = "1";
            vm.getobj(res.data.data[0]);
            let arr = [];
            if (res.data.data[0].discernName != null) {
              res.data.data[0].discernName.split('#').forEach(e => {
                let z = {
                  value: e
                }
                arr.push(z)
              })
              localStorage.setItem('arr', JSON.stringify(arr));
            }
            if (res.data.data[0].discernPath != null) {
              vm.bigimage = res.data.data[0].discernPath;
            } else {
              vm.bigimage = res.data.data[0].accessorySrc;
            }
            vm.animalData.url = res.data.data[0].accessorySrc;
            vm.messageObj = Object.assign({}, res.data.data[0]);
            vm.imageList = res.data.data;
            let w = res.data.data.length * 1.6;
            $('.viewpager_container').css("width", w + "rem");
            let look_b_i = [];
            let ims = res.data.data[0].accessorySrc
            look_b_i.push(ims);
            vm.signImages = look_b_i;
            $(function () {
              let maxWidth = $('.big_image').width();
              let maxHeight = $('.big_image').height();
              let path = $('#pcr').attr('src');
              vm.AutoSize(path, maxWidth, maxHeight);
            })
          } else {
            vm.islast = false;
            vm.success('该类物种已全部鉴定完毕')
            setTimeout(function () {
              vm.goback();
            }, 2000)
          }
        })()
      },
      //获取对象值
      getobj(o) {
        for (let k in o) {
          if (k == 'objType' && o[k] == null) {
            o[k] = '兽类'
          }
          if (k == 'aloneAuthenticate' && o[k] == null) {
            o[k] = 0;
            this.single = false
          }

          if (k == 'identifyPeople' && o[k] == null) {
            o[k] = this.userName;
          }
          if (k == 'aloneAuthenticate' && o[k] != null) {
            if (o[k] = 1) {
              this.single = true
            } else if (o[k] = 0) {
              this.single = false
            }
          }

        }
        this.change_time = o.shootingTime;
        this.ruleForm = o;

        if (this.ruleForm.discernName != null) {
          this.ruleForm.speciesName = this.ruleForm.discernName.split('#')[0];
        }

      },
      //运动
      movement(t, i) {
        this.imageList.forEach(e => {
          e.color = '0'
        });
        t.color = '1';
        this.indexes = i;
        this.getobj(t);
        if (t.discernPath != null) {
          this.bigimage = t.discernPath;
        } else {
          this.bigimage = t.accessorySrc;
        }

        this.animalData.url = t.accessorySrc;
        let look_b_i = [];
        let ims = t.accessorySrc
        look_b_i.push(ims);
        this.signImages = look_b_i;
        this.messageObj = Object.assign({}, t);
        let target = $('.viewpager_container');
        if (i >= 3) {
          target.stop().animate({left: -(i - 2) * 1.6 + "rem"}, 500)
        } else {
          target.stop().animate({left: 0}, 500)
        }
        this.rm = 0;
        $("#pcr").css("transform", "rotate(0deg)");
        let vm = this;
        $(function () {
          let maxWidth = $('.big_image').width();
          let maxHeight = $('.big_image').height();
          let path = $('#pcr').attr('src');
//          if (vm.isMp4(vm.Pictures) == '照片') {
          vm.AutoSize(path, maxWidth, maxHeight);
//          }
        })

      },
      del() {
        let id = this.imageList[this.indexes].id;
        let vm = this;
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          (async function () {
            let res = await http.post(api.infrared.newimageIdentifyDelete,
              {
                id: id
              }
            )
            if (res.data.message == 'error') {
              vm.warn(res.data.error)
            } else {
              vm.refreshdata();
              vm.$message({
                type: 'success',
                message: '删除成功!'
              });
              vm.getdata();
            }
          })()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      goback() {
        this.$router.push({
          path: '/Photo/classify',
        });
      },
      //图片处理
      iscloud(p) {
        if (p.split(":")[0] == 'http') {
          return p + '@oosImage|100h'
        }
        if (p.split(":")[0] == 'https') {
          return p + '?x-amz-process=image/resize,h_100,m_lfit'
        }
        return '/iapi' + p
      },
      //时间处理
      c_time(e) {
        let a = (new Date(e))
        return a;
      },
      //获取时间
      gettime(datetime) {
        if (datetime != null) {
          let year = datetime.getFullYear();
          let month = datetime.getMonth() + 1;
          let date = datetime.getDate();
          let Hours = datetime.getHours();
          let Minutes = datetime.getMinutes();
          let Seconds = datetime.getSeconds();

          if (month >= 1 && month <= 9) {
            month = "0" + month;
          }
          if (date >= 0 && date <= 9) {
            date = "0" + date;
          }
          if (Hours >= 1 && Hours <= 9) {
            Hours = "0" + Hours;
          }
          if (Minutes >= 0 && Minutes <= 9) {
            Minutes = "0" + Minutes;
          }
          if (Seconds >= 1 && Seconds <= 9) {
            Seconds = "0" + Seconds;
          }
          let t1 = year + "/" + month + "/" + date + " " + Hours + ":" + Minutes + ":" + Seconds;
          this.change_time = t1;
        } else {
          this.change_time = ''
        }

      },
      warn(txt) {
        this.$message({
          message: txt,
          type: 'warning'
        });
      },
      success(txt) {
        this.$message({
          message: txt,
          type: 'success'
        });
      },
    }
  }
</script>
<style scoped>
  @import "../../static/css/authenticate.css";
</style>

